/* eslint-disable */
const { list } = require('./src/mock/mock.js')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const userList = [{
	username: '张三',
	password: '123456'
}, {
	username: '1909A',
	password: '33'
}, {
	username: 'admin',
	password: 'admin'
}]
module.exports = {
	devServer: {
		before(app) {
			app.use(bodyParser.json())
			// 列表访问接口
			app.get('/api/list', (req, res) => {
				const { pageCode = 1, pageSize = 10 } = req.query
				console.log(pageCode, pageSize, list.length)
				if (pageCode * pageSize <= list.length && pageCode >= 1) {
					res.send({
						code: 200,
						data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize)
					})
				} else {
					res.send({
						code: 1,
						data: null,
						mess: '没有更多数据了！！！'
					})
				}

			})

			// 跳转详情接口
			app.post('/api/detail', (req, res) => {
				const { id } = req.body;
				const item = list.find(v => v.id === id)
				if (item) {
					res.send({
						code: 200,
						data: item
					})
				} else {
					res.send({
						code: 404,
						data: null,
						mess: '该商品已经下架！！！'
					})
				}
			})

			// 登录接口
			app.post('/api/user/login', (req, res) => {
				const { username, password } = req.body

				const currUser = userList.find(v => v.username === username && v.password === password)

				if (currUser) {
					res.send({
						code: 200,
						data: {
							username: currUser.username,
							token: JWT.sign({ username: currUser.username }, '666666')
						}
					})
				} else {
					res.send({
						code: 403,
						data: null,
						mess: '账户或者密码不正确, 请重新登录'
					})
				}

			})


			// 评论接口
			app.post('/my/message', (req, res) => {
				
				const { id, data } = req.body;
				const currItem = list.find(v => v.id === id)

				if (currItem) {
					currItem.messageList.unshift(data);
					res.send({
						code: 200,
						data: null,
						mess: '添加评论成功'
					})
				} else {
					res.send({
						code: 403,
						data: null,
						mess: '添加评论失败'
					})
				}
			})


		},
		proxy: {
			'/api': {
				target: 'https://m.dcdapp.com/motor/brand/m/v1/brand/?device_id=0',
				pathRewrite: { '^/api': '' },
			},

			'/detail': {
				target: 'https://m.dcdapp.com/motor/brand/m/v5/brand_series_list/',
				pathRewrite: { '^/detail': '' },
			}
		},
	}
}